<template>
  <div id="div1">
    <div id="div1-1">
      <vxe-button class="div1-1-button1" @click="addAuth">新增权限</vxe-button>
      <vxe-button class="div1-1-button2" @click="delAuth">删除权限</vxe-button>
      <vxe-button class="div1-1-button3" @click="saveAuth">保存</vxe-button>
    </div>
    <div id="div1-2">
      <vxe-table keep-source ref="t1Ref" height="100%" :edit-config="{ trigger: 'click', mode: 'cell',activeMethod:()=>true }"
                 @checkbox-change="changeAuth" :checkbox-config="{ highlight: true }" auto-resize :data="tableData">
        <vxe-table-column type="checkbox" width="60"></vxe-table-column>
        <vxe-table-column type="seq" width="60"></vxe-table-column>
        <vxe-table-column field="authname" title="权限名称" :edit-render="{
                                immediate: true,
                                name: 'input',
                                attrs: {type: 'text'}

        }">
        </vxe-table-column>
        <vxe-table-column field="status" title="状态" :edit-render="{
                               immediate: true,
                                name: '$select',
                                props: {type: 'select'},
                                options: statusOptions,
                                events: {
                                }
        }"></vxe-table-column>
        <vxe-table-column field="description" title="描述" :edit-render="{
                                immediate: true,
                                name: 'input',
                                attrs: {type: 'text'}
        }"></vxe-table-column>
        <vxe-table-column align="center" header-align="center" :width="300" title="操作">
          <template slot-scope="scope">
            <div style="text-align: center;width: 100%;">
              <el-button size="mini" @click="selectOperation(scope)">接口</el-button>
              <el-button size="mini" @click="selectMenu(scope)">菜单</el-button>
              <el-button size="mini" @click="selectView(scope)">资源</el-button>
            </div>
          </template>
        </vxe-table-column>
      </vxe-table>
    </div>
    <el-dialog title="选择接口" :visible.sync="selectOperationShow" center>
      <el-table ref="t2Ref" :data="operationData" class="basic-table" max-height="300" @selection-change="changeOperation">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column property="operationname" label="接口名" width="150"></el-table-column>
        <el-table-column property="method" label="方式" width="150"></el-table-column>
        <el-table-column property="path" label="路径"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="selectOperationShow = false">取 消</el-button>
        <el-button type="primary" @click="saveAuthOperations">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="选择资源" :visible.sync="selectViewShow" center>
      <el-table ref="t3Ref" :data="viewData" class="basic-table" max-height="300" @selection-change="changeView">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column property="module" label="模块" width="150"></el-table-column>
        <el-table-column property="viewName" label="资源名" width="150"></el-table-column>
        <el-table-column property="type" label="类型" width="150"></el-table-column>
        <el-table-column property="routerPath" label="路由地址"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="selectViewShow = false">取 消</el-button>
        <el-button type="primary" @click="saveAuthViews">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: "AuthList",
  data() {
    return {
      statusOptions: [
        {label: '正常', value: '1'},
        {label: '禁用', value: '0'},
      ],
      tableData: [
        {id:'1',authname: '系统管理员', status:'0',description: '系统管理员权限'},
      ],
      selectedData: [],
      // 点击操作列按钮时，记录点击的权限
      selectedAuth: '',
      // 选择接口的对话框是否显示
      selectOperationShow: false,
      // 接口表
      operationData: [],
      // 选中的接口
      changedOperations:[],
      // 选择资源的对话框是否显示
      selectViewShow: false,
      // 接口表
      viewData: [],
      // 选中的接口
      changedViews:[],
    }
  },
  mounted() {
    this.loadData();
  },
  computed: {},
  methods: {
    addAuth() {
      const self = this;
      self.$refs.t1Ref.insertAt({}, -1);
    },
    delAuth() {
      const self = this;
      self.$refs.t1Ref.removeCheckboxRow();
    },
    changeAuth({records}) {
      this.selectedData = records;
      console.log('rows', JSON.stringify(records))
    },
    changeAllAuth(records) {
      console.log('all', JSON.stringify(records));
    },
    loadData() {
      request({
        url: '/user/auth',
        method: 'get',
        params: {
          size: -1
        }
      }).then(response => {
        if (response && response.data) {
          console.log('response', response);
          const tempList = [];
          response.data.records.forEach(item => {
            tempList.push({
              id: item.id,
              authname: item.authname,
              description: item.description,
              status: item.status
            })
          })
          this.tableData = tempList;
        }
      }).catch(error => {
        console.log('error', error);
        this.$message.error('加载数据失败')
      })
    },
    saveAuth() {
      const self = this;
      const {
        insertRecords,
        updateRecords,
        removeRecords
      } = JSON.parse(JSON.stringify(self.$refs.t1Ref.getRecordset()));
      request({
        url: '/user/auth/batch',
        method: 'post',
        data: {
          insertAndUpdate: updateRecords.concat(insertRecords),
          del: removeRecords
        }
      }).then(response => {
        if (response && response.data) {
          this.$message.success('保存成功');
          this.loadData();
        }
      }).catch(error => {
        console.log('error', error);
        this.$message.error('保存失败')
      })
    },
    loadOperationData(callBack){
      request({
        url: '/user/operation',
        method: 'get',
        params: {
          size: -1
        }
      }).then(response => {
        if (response && response.data) {
          const tempList = [];
          response.data.records.forEach(item => {
            tempList.push({
              id: item.id,
              operationname: item.operationname,
              method: item.method,
              path: item.path,
            })
          })
          this.operationData = tempList;
        }
        if (callBack && typeof callBack === 'function') {
          callBack();
        }
      }).catch(error => {
        console.log('error', error);
        this.$message.error('加载数据失败')
      })
    },
    selectOperation(scope) {
      const self = this;
      // 保存操作的用户信息
      self.selectedAuth = scope.row;
      self.loadOperationData(() => {
        // 打开弹窗
        self.selectOperationShow = true;
        this.$nextTick(()=>{
          // 先清空现有选择
          self.$refs.t2Ref.clearSelection();
          // 获取用户下角色
          request({
            url: '/user/authOperation',
            method: 'get',
            params: {
              authId: scope.row.id,
              size: -1
            },
          }).then(response => {
            if (response && response.data) {
              console.log('response', response)
              const operationIds= response.data.records.map(item => item.operationId);
              console.log('operationIds', operationIds);
              console.log('operationData', self.operationData);
              self.operationData.forEach(row => {
                if (operationIds.includes(row.id)){
                  self.$refs.t2Ref.toggleRowSelection(row, true);
                }
              });
            }
          }).catch(error => {
            console.log('error', error);
            this.$message.error('加载数据失败')
          });
        });
      })
    },
    changeOperation(val){
      const self = this;
      self.changedOperations = val;
    },
    saveAuthOperations(){
      const self = this;
      const authId = self.selectedAuth.id;
      let authOperations = [];
      if (self.changedOperations.length === 0){
        authOperations = [{authId:authId}];
      }else {
        authOperations = self.changedOperations.map(item => {
          return {
            authId: authId,
            operationId: item.id
          }
        });
      }
      request({
        url: '/user/authOperation/batch',
        method: 'post',
        data: authOperations
      }).then(response => {
        if (response && response.data) {
          this.$message.success('保存成功');
          self.selectOperationShow = false;
        }
      }).catch(error => {
        console.log('error', error);
        this.$message.error('保存失败')
      })
    },

    loadViewData(callBack){
      request({
        url: '/user/view',
        method: 'get',
        params: {
          size: -1
        }
      }).then(response => {
        if (response && response.data) {
          const tempList = [];
          response.data.records.forEach(item => {
            tempList.push({
              id: item.id,
              module: item.module,
              viewName: item.viewName,
              type: item.type,
              routerPath: item.routerPath,
            })
          })
          this.viewData = tempList;
        }
        if (callBack && typeof callBack === 'function') {
          callBack();
        }
      }).catch(error => {
        console.log('error', error);
        this.$message.error('加载数据失败')
      })
    },
    selectView(scope) {
      const self = this;
      // 保存操作的用户信息
      self.selectedAuth = scope.row;
      self.loadViewData(() => {
        // 打开弹窗
        self.selectViewShow = true;
        this.$nextTick(()=>{
          // 先清空现有选择
          self.$refs.t3Ref.clearSelection();
          // 获取用户下角色
          request({
            url: '/user/authView',
            method: 'get',
            params: {
              authId: scope.row.id,
              size: -1
            },
          }).then(response => {
            if (response && response.data) {
              console.log('response', response)
              const viewIds= response.data.records.map(item => item.viewId);
              console.log('viewIds', viewIds);
              console.log('viewData', self.viewData);
              self.viewData.forEach(row => {
                if (viewIds.includes(row.id)){
                  self.$refs.t3Ref.toggleRowSelection(row, true);
                }
              });
            }
          }).catch(error => {
            console.log('error', error);
            this.$message.error('加载数据失败')
          });
        });
      })
    },
    changeView(val){
      const self = this;
      self.changedViews = val;
    },
    saveAuthViews(){
      const self = this;
      const authId = self.selectedAuth.id;
      const authViews = self.changedViews.map(item => {
        return {
          authId: authId,
          viewId: item.id
        }
      });
      request({
        url: '/user/authView/batch',
        method: 'post',
        data: authViews
      }).then(response => {
        if (response && response.data) {
          this.$message.success('保存成功');
          self.selectViewShow = false;
        }
      }).catch(error => {
        console.log('error', error);
        this.$message.error('保存失败')
      })
    }
  }
}
</script>

<style scoped>
#div1{
  width: 100%;
  height: 100%;
  position: relative;
}

#div1-1{
  width: 100%;
  height: 10%;
  margin-bottom: 10px;
  position: relative;
  overflow: hidden;
}
.div1-1-button1{
  top: 20px;
  right: 20px;
  width: 80px;
  position: absolute;
}

.div1-1-button2{
  top: 20px;
  right: 120px;
  position: absolute;
  width: 80px;
}

.div1-1-button3{
  top: 20px;
  right: 230px;
  position: absolute;
  width: 80px;
}

#div1-2 {
  width: 100%;
  height: Calc(90% - 10px)  ;
  background-color: #606376;
  border-radius: 10px;
  padding: 10px;
  position: absolute;
}

#div1-2 .vxe-table{
}

::v-deep .vxe-table--header-wrapper {
  background-color: #606376 !important;
}
::v-deep .vxe-table--header-wrapper .vxe-header--row {
  background-color: #606376 !important;
  color: white;
}
::v-deep .vxe-table--body-wrapper{
  background-color: #606376 !important;
}
::v-deep .vxe-table--body-wrapper .vxe-body--row {
  background-color: #606376 !important;
  color: white;
}

</style>